/**
 * Sidebar - 侧边栏组件
 * 显示所有会话列表，提供会话管理功能
 */
import React from 'react';
import { motion, AnimatePresence } from "motion/react";
import { MessageSquare, X, Trash2 } from 'lucide-react';
import { useChatContext } from '../ctx/ChatContext';

interface SidebarProps {
    isOpen: boolean;
    onClose: () => void;
}

const Sidebar: React.FC<SidebarProps> = ({ isOpen, onClose }) => {
    const { conversations, currentConversation, selectConversation, deleteConversation } = useChatContext();

    // 格式化日期
    const formatDate = (dateString: string) => {
        const date = new Date(dateString);
        return date.toLocaleDateString();
    };

    // 获取消息预览
    const getMessagePreview = (messages: any[]) => {
        if (messages.length === 0) return '无消息';
        return messages[0].content.length > 30
            ? messages[0].content.substring(0, 30) + '...'
            : messages[0].content;
    };

    return (
        <>
            {/* Overlay for mobile */}
            <AnimatePresence>
                {isOpen && (
                    <motion.div
                        initial={{ opacity: 0 }}
                        animate={{ opacity: 1 }}
                        exit={{ opacity: 0 }}
                        className="fixed inset-0 bg-black/20 z-10 md:hidden"
                        onClick={onClose}
                    />
                )}
            </AnimatePresence>

            {/* Sidebar - 移动端可收起，桌面端固定显示 */}
            <motion.aside
                initial={{ x: '-100%' }}
                animate={{
                    x: isOpen ? 0 : '-100%'
                }}
                transition={{ type: 'spring', bounce: 0, duration: 0.4 }}
                className={`
          fixed top-0 left-0 z-20
          w-80 h-full bg-white border-r border-gray-200 
          flex flex-col
          md:relative md:translate-x-0 md:flex
          ${!isOpen ? 'hidden' : ''}
        `}
            >
                <div className="p-4 border-b border-gray-200 flex items-center justify-between h-16">
                    <h2 className="font-semibold text-xl">对话历史</h2>
                    <button
                        onClick={onClose}
                        className="p-2 rounded-full hover:bg-gray-100 md:hidden"
                        aria-label="关闭侧边栏"
                    >
                        <X size={20} />
                    </button>
                </div>

                <div className="flex-1 overflow-y-auto p-3 space-y-2">
                    {conversations.length === 0 ? (
                        <div className="text-center text-gray-500 py-10">
                            <p>暂无对话历史</p>
                        </div>
                    ) : (
                        conversations.map(conversation => (
                            <motion.div
                                key={conversation.id}
                                whileHover={{ scale: 1.02 }}
                                whileTap={{ scale: 0.98 }}
                                className={`
                  p-3 rounded-xl cursor-pointer relative group
                  ${currentConversation?.id === conversation.id
                                        ? 'bg-blue-100 border-blue-200 border'
                                        : 'hover:bg-gray-100 border border-transparent hover:border-gray-200'}
                `}
                                onClick={() => {
                                    selectConversation(conversation.id);
                                    // onClose();
                                }}
                            >
                                <div className="flex items-start gap-3">
                                    <div className="w-10 h-10 rounded-full bg-gradient-to-br from-blue-500 to-purple-600 flex items-center justify-center flex-shrink-0">
                                        <MessageSquare size={20} className="text-white" />
                                    </div>
                                    <div className="flex-1 min-w-0">
                                        <h3 className="font-medium text-sm truncate">{conversation.title}</h3>
                                        <p className="text-xs text-gray-500 mt-1 truncate">
                                            {conversation.messages.length > 0
                                                ? getMessagePreview(conversation.messages)
                                                : '开始一个新对话...'}
                                        </p>
                                        <p className="text-xs text-gray-400 mt-1">
                                            {formatDate(conversation.createdAt)}
                                        </p>
                                    </div>
                                </div>

                                {/* Delete button */}
                                <button
                                    onClick={(e) => {
                                        e.stopPropagation();
                                        deleteConversation(conversation.id);
                                    }}
                                    className="absolute top-2 right-2 opacity-0 group-hover:opacity-100 p-1.5 rounded-full hover:bg-red-100 text-red-500"
                                    aria-label="删除对话"
                                >
                                    <Trash2 size={16} />
                                </button>
                            </motion.div>
                        ))
                    )}
                </div>

                <div className="p-4 bg-gray-50 text-xs text-gray-500 text-center border-t border-gray-200">
                    AI 聊天助手 © {new Date().getFullYear()}
                </div>
            </motion.aside>
        </>
    );
};

export default Sidebar;